package net.apexcns.core.spring;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.apexcns.core.web.util.ServletUtil;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public abstract class CoreAbstractController extends AbstractController {
	private WebBindingInitializer webBindingInitializer;

	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return execute(request, response);
	}

	protected abstract ModelAndView execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception;

	protected void bind(HttpServletRequest request, Object command) throws Exception {
		ServletUtil.setRequestInfo(request, command);
	}

	protected void bind(HttpServletRequest request, Object ... commands) throws Exception {
		if(commands == null) return;
		for(Object command : commands) {
			ServletUtil.setRequestInfo(request, command);
		}
	}

	protected void bindRequest(HttpServletRequest request, Object command)
	throws Exception {
		ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
		if (this.webBindingInitializer != null)
			this.webBindingInitializer.initBinder(binder, new ServletWebRequest(request));
		binder.bind(request);
		binder.closeNoCatch();
	}

}
